﻿//-----------------------------------------------------------------------
// <copyright file="baseupdownfielddefinition.cs" company="Jamie Knight">
// Copyright (c) Jamie Knight. All rights reserved.
// </copyright>
//-----------------------------------------------------------------------

using System.ComponentModel.DataAnnotations;
using System.Windows.Data;
using DevKnightlie.WPF.AutoForm.FieldDefinitions;
using Xceed.Wpf.Toolkit.Primitives;

namespace DevKnightlie.WPF.AutoForm.WPFToolkit.FieldDefinitions
{
    /// <summary>
    /// Base field definition for creating WPFToolkit UpDown controls
    /// </summary>
    /// <typeparam name="T"></typeparam>
    public abstract class BaseUpDownFieldDefinition<T>:BaseFieldDefinition
    {
        #region Properties

        /// <summary>
        /// Gets or sets the ability to perform increment/decrement operations via the keyboard, button spinners, or mouse wheel
        /// </summary>
        public bool AllowSpin { get; set; }

        /// <summary>
        /// Minimum value for the input control
        /// </summary>
        public T Minimum { get; set; }

        /// <summary>
        /// Maximum value for the input control
        /// </summary>
        public T Maximum { get; set; }

        #endregion

        #region Methods

        /// <summary>
        /// Return an instance of the desired UpDownBase-derived control
        /// </summary>
        /// <returns>UpDownBase-descendant</returns>
        protected abstract UpDownBase<T> CreateInputControl();


        public override void BuildInputControl()
        {
            UpDownBase<T> control = CreateInputControl();
            control.Minimum = Minimum;
            control.Maximum = Maximum;
            control.AllowSpin = AllowSpin;
            if (PropertyInfo != null)
            {
                // See if there's a Range attribute against the property
                var attrs = (RangeAttribute[])PropertyInfo.GetCustomAttributes(typeof(RangeAttribute), false);
                if (attrs.Length > 0)
                {
                    RangeAttribute attr = attrs[0];
                    control.Minimum = (T)attr.Minimum;
                    control.Maximum = (T)attr.Maximum;
                }
            } 
            Binding valueBinding = new Binding(PropertyName);
            BindingOperations.SetBinding(control, UpDownBase<T>.ValueProperty, valueBinding);
            SetupEnabledBinding(control);
            ContainerControl = InputControl = control;
        }

        #endregion
    }
}
